<template>
  <div class="m-8">
    <SearchDemo
      v-model="searchName"
      placeholder="名称"
      @searchInput="searchInput('role')"
      @claerInput="claerInput('role')"
    />
    <div>
      <el-button id="b3" type="primary" class="px-4 py-2 mt-8" @click="openAddDialog('role')">
        添加
      </el-button>
      <el-dialog
        v-model="addBox"
        :title="dialogTitle"
        width="500"
        align-center
        @close="handleClose"
      >
        <el-form :model="form" label-width="auto" ref="formRef">
          <el-form-item
            label="角色名:"
            prop="inputname"
            :rules="{
              required: true,
              message: '角色名不可为空',
              trigger: 'blur'
            }"
          >
            <el-input v-model="form.inputname" placeholder="角色名称" clearable />
          </el-form-item>

          <el-form-item label="描述:">
            <el-input v-model="inputDescription" placeholder="描述" clearable />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleClose" class="px-4 py-2 mr-3"> 取消 </el-button>
            <el-button type="primary" @click="submit(formRef)"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <el-table
      :data="tableData"
      stripe
      class="w-full mt-2"
      border
      :header-cell-style="{ 'text-align': 'center', height: '60px' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column prop="name" label="角色列表" width="400px" />
      <el-table-column prop="description" label="描述" width="900px" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button
            type="primary"
            class="!p-2 text-base font-bold"
            text
            visible="false"
            @click="openEditDialog(row)"
          >
            编辑
          </el-button>

          <el-button
            type="danger"
            class="!p-2 text-base font-bold"
            text
            visible="false"
            @click="delroles(row)"
          >
            删除
          </el-button>

          <el-button
            type="success"
            class="!p-2 text-base font-bold"
            text
            visible="false"
            @click="showDrawer(row)"
          >
            分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <el-drawer title="分配权限" v-model="drawer" size="20%">
    <div>
      <el-checkbox-group v-model="checkList">
        <div>
          <el-checkbox v-for="(value, key) in priviList" :key="key" :label="value" :value="key" />
        </div>
      </el-checkbox-group>
    </div>
    <template #footer>
      <div class="drawer-footer">
        <el-button type="primary" @click="givePrivi"> 确定 </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { createOneRole, deleteRole, upDateRole, getRolePrivi, updataRolePrivi } from '@/api/role'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { reactive, ref } from 'vue'
import { priviList } from '../../shared/privileges'
import SearchDemo from './components/SearchDemo.vue'
import { useTable } from '@/composables/useTable'

let {
  tableData,
  getTableData,
  claerInput,
  searchName,
  searchInput,
  openAddDialog,
  isAdd,
  addBox,
  dialogTitle,
  drawer
} = useTable()

const inputDescription = ref('')
const formRef = ref<FormInstance>()

let editId = 0
let roleId = 0
let checkList = ref<any[]>([])

const form = reactive({
  inputname: ''
})

//获取所有角色信息
getTableData('role')

//打开编辑弹窗
function openEditDialog(row: { id: any; name: any; description: any }) {
  addBox.value = true
  dialogTitle.value = '编辑角色'
  isAdd.value = false
  form.inputname = row.name
  inputDescription.value = row.description
  editId = row.id
}

//弹窗确认添加角色或编辑角色
const submit = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // 表单校验
  formEl.validate((valid) => {
    if (valid) {
      if (isAdd.value) {
        surecreateRole()
      } else {
        updateRole()
      }
    }
  })
}

//关闭弹窗
const handleClose = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  form.inputname = ''
  inputDescription.value = ''
  addBox.value = false
}

//新增一条角色信息
async function surecreateRole() {
  const data = {
    name: form.inputname,
    description: inputDescription.value
  }
  await createOneRole(data)
  getTableData('role')
  handleClose()
}

//编辑指定角色信息
async function updateRole() {
  const id = editId
  const data = {
    name: form.inputname,
    description: inputDescription.value
  }
  await upDateRole(id, data)
  getTableData('role')
  handleClose()
}

//删除一条角色信息
function delroles(row: { id: any }) {
  ElMessageBox.confirm('确定要删除此条角色信息吗？', '注意', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    cancelButtonClass: 'cancel-btn',
    type: 'warning',
    center: true
  })
    .then(async () => {
      await deleteRole(row.id)
      ElMessage({
        type: 'success',
        message: '成功删除'
      })
      claerInput('role')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}

//打开分配权限抽屉、获取当前角色id的权限信息
async function showDrawer(row: { id: any }) {
  checkList.value = []
  drawer.value = true
  roleId = row.id
  const data = await getRolePrivi(roleId)
  if (data.data === '') return
  const newdata = data.data.split(',')
  checkList.value = newdata
}

//分配权限
async function givePrivi() {
  const params = {
    roleId: roleId,
    resourceIds: checkList.value.join()
  }
  await updataRolePrivi(params)
  drawer.value = false
  ElMessage({
    message: '分配成功',
    type: 'success'
  })
}
</script>

<style scoped></style>
